package com.kf.service.Impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.kf.pojo.Notice;
import com.kf.pojo.User;
import com.kf.pojo.form.NoticeForm;
import com.kf.service.CommonService;
import com.kf.service.NoticeRepository;
import org.apache.ibatis.annotations.Result;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 公共服务impl
 *
 * @author Honey
 * @date 2022/12/23
 */
@Service
public class CommonServiceImpl implements CommonService {

    @Resource
    @Qualifier("restHighLevelClient")
    RestHighLevelClient restHighLevelClient;
    @Resource
    NoticeRepository noticeRepository;
    @Override
    public List<NoticeForm> getMyNotice(String notice, User user) throws IOException {

        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("kang_index");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(notice, "username", "noticeTopic","noticeContent","createby");

        multiMatchQueryBuilder.operator(Operator.OR);
        searchSourceBuilder.query(multiMatchQueryBuilder);
        searchSourceBuilder.sort("id", SortOrder.DESC);

        searchRequest.source(searchSourceBuilder);

        //4.执行查询
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //5.解析查询结果file
        System.out.println("花费的时长：" + searchResponse.getTook());

        ArrayList<NoticeForm> list = new ArrayList<>();
        ArrayList<NoticeForm> list1 = new ArrayList<>();

        SearchHits hits = searchResponse.getHits();
        System.out.println("符合条件的总文档数量：" + hits.getTotalHits().value);
        hits.forEach(p -> System.out.println("文档原生信息：" + p.getSourceAsString()));

        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            JSONObject object = JSON.parseObject(json);
            String target = object.getString("target");
            if(!"2".equals(target)){
                String id=object.getString("id");
                String username = object.getString("username");
                String createby = object.getString("createby");
                String noticeTopic = object.getString("noticeTopic");
                String noticeContent = object.getString("noticeContent");
                String createtime = object.getString("createtime");
                NoticeForm noticeForm = new NoticeForm();
                noticeForm.setId(id);
                noticeForm.setUsername(username);
                noticeForm.setCreateby(createby);
                noticeForm.setTarget(target);
                noticeForm.setNoticeTopic(noticeTopic);
                noticeForm.setNoticeContent(noticeContent);
                noticeForm.setCreatetime(createtime);
                list.add(noticeForm);
            }
                String username = object.getString("username");
                String createby = object.getString("createby");
                String id=object.getString("id");
                String noticeTopic = object.getString("noticeTopic");
                String noticeContent = object.getString("noticeContent");
                String createtime = object.getString("createtime");
                NoticeForm noticeForm = new NoticeForm();
                noticeForm.setId(id);
                noticeForm.setUsername(username);
                noticeForm.setCreateby(createby);
                noticeForm.setTarget(target);
                noticeForm.setNoticeTopic(noticeTopic);
                noticeForm.setNoticeContent(noticeContent);
                noticeForm.setCreatetime(createtime);
                System.out.println("0 1 2" +noticeForm);
                list1.add(noticeForm);

        }
        if(user.getState()==1){
            return list;
        }else{
            return list1;
        }
    }

    @Override
    public List<Notice> getAllNotice(User user){

        ArrayList<Notice> list = new ArrayList<>();
        ArrayList<Notice> list1 = new ArrayList<>();
        Iterable<Notice> all = noticeRepository.findAll();
        for (Notice notice : all) {
            if(notice.getTarget()==1||notice.getTarget()==0){
                list1.add(notice);
            }
            list.add(notice);
        }

        if(user.getState()==1){
            list1.sort(Comparator.comparing(Notice::getHeat));
            Collections.reverse(list1);

            return list1;
        }else {
            list.sort(Comparator.comparing(Notice::getHeat));
            Collections.reverse(list);
            return list;
        }



    }
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
    @Override
    public Boolean send( Map<String, Object> param,String phone) throws Exception {

 com.aliyun.dysmsapi20170525.Client client = CommonServiceImpl.createClient("LTAI5tC38ZhnjbeYMx5bJoNK", "ute0WFl7TcB2lq5NkZKLa0hsP9dKQA");
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setSignName("GDPMS")
                    .setTemplateCode("SMS_264100763")
                    .setPhoneNumbers(phone)
                    .setTemplateParam(JSONObject.toJSONString(param));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            try {
                // 复制代码运行请自行打印 API 的返回值
                SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
                System.out.println(sendSmsResponse);
                return true;
            } catch (TeaException error) {
                // 如有需要，请打印 error
                com.aliyun.teautil.Common.assertAsString(error.message);
                return false;
            } catch (Exception error) {
                TeaException error1 = new TeaException(error.getMessage(), error);
                // 如有需要，请打印 error
                com.aliyun.teautil.Common.assertAsString(error1.message);
                return false;

            }

    }
}
